"""
用户数据模型
============

定义用户相关的数据库模型
"""

from datetime import datetime, timezone
from typing import Optional
from sqlalchemy import String, Boolean, DateTime, Integer, Float, JSON
from sqlalchemy.orm import Mapped, mapped_column, relationship

from redfire_framework.core.database import Base


class User(Base):
    """用户模型"""
    __tablename__ = "users"
    
    # 基本信息
    id: Mapped[str] = mapped_column(String(36), primary_key=True)
    username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
    email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
    phone: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
    full_name: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
    
    # 安全相关
    password_hash: Mapped[str] = mapped_column(String(255))
    email_verified: Mapped[bool] = mapped_column(Boolean, default=False)
    phone_verified: Mapped[bool] = mapped_column(Boolean, default=False)
    status: Mapped[str] = mapped_column(String(20), default="pending_verification", index=True)
    primary_role: Mapped[str] = mapped_column(String(20), default="viewer")
    
    # 双因素认证
    two_factor_enabled: Mapped[bool] = mapped_column(Boolean, default=False)
    two_factor_secret: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    
    # 密码重置
    password_reset_token: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    password_reset_expires: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
    email_verification_token: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    
    # 账户安全
    failed_login_attempts: Mapped[int] = mapped_column(Integer, default=0)
    account_locked_until: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
    force_password_change: Mapped[bool] = mapped_column(Boolean, default=False)
    
    # 用户偏好设置
    timezone: Mapped[str] = mapped_column(String(50), default="UTC")
    language: Mapped[str] = mapped_column(String(10), default="zh-CN")
    theme: Mapped[str] = mapped_column(String(20), default="light")
    
    # 交易限制
    max_positions: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
    max_order_value: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
    daily_loss_limit: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
    
    # 元数据
    metadata_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
    
    # 时间戳
    created_at: Mapped[datetime] = mapped_column(
        DateTime, 
        default=lambda: datetime.now(timezone.utc)
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime,
        default=lambda: datetime.now(timezone.utc),
        onupdate=lambda: datetime.now(timezone.utc)
    )
    last_login_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
    last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
    
    # 向后兼容的属性别名
    @property
    def hashed_password(self) -> str:
        """向后兼容：返回password_hash"""
        return self.password_hash
    
    @hashed_password.setter
    def hashed_password(self, value: str):
        """向后兼容：设置password_hash"""
        self.password_hash = value
    
    @property
    def is_active(self) -> bool:
        """向后兼容：根据status判断用户是否激活"""
        return self.status == "active"
    
    @property
    def last_login(self) -> Optional[datetime]:
        """向后兼容：返回last_login_at"""
        return self.last_login_at
    
    @last_login.setter
    def last_login(self, value: Optional[datetime]):
        """向后兼容：设置last_login_at"""
        self.last_login_at = value
    
    def __repr__(self) -> str:
        return f"<User(id={self.id}, username={self.username}, email={self.email})>"
